<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAlbumStore } from '../stores/album'
import { gsap } from 'gsap'

const route = useRoute()
const router = useRouter()
const albumStore = useAlbumStore()

const photoId = computed(() => Number(route.params.id))
const albumId = computed(() => Number(route.query.albumId))

const album = computed(() => albumStore.getAlbumById(albumId.value))
const photo = computed(() => {
  if (!album.value) return null
  return album.value.photos.find(p => p.id === photoId.value)
})

// 获取前一张和后一张照片
const prevPhoto = computed(() => {
  if (!album.value) return null
  const currentIndex = album.value.photos.findIndex(p => p.id === photoId.value)
  if (currentIndex <= 0) return null
  return album.value.photos[currentIndex - 1]
})

const nextPhoto = computed(() => {
  if (!album.value) return null
  const currentIndex = album.value.photos.findIndex(p => p.id === photoId.value)
  if (currentIndex === -1 || currentIndex === album.value.photos.length - 1) return null
  return album.value.photos[currentIndex + 1]
})

const photoRef = ref<HTMLElement | null>(null)
const infoRef = ref<HTMLElement | null>(null)
const controlsRef = ref<HTMLElement | null>(null)
const containerRef = ref<HTMLElement | null>(null)

interface Photo {
  id: number;
  title: string;
  url?: string;
  description?: string;
  date?: string;
}

const navigateToPhoto = (photo: Photo | null) => {
  if (!photo) return
  // 添加页面跳转动画
  gsap.to('.photo-view', {
    opacity: 0, duration: 0.5, onComplete: () => {
      router.push(`/photo/${photo.id}?albumId=${albumId.value}`)
    }
  })
}

const goBack = () => {
  // 添加返回动画
  gsap.to('.photo-view', {
    opacity: 0, duration: 0.5, onComplete: () => {
      router.push('/gallery')
    }
  })
}

const handleMouseMove = (e: MouseEvent) => {
  if (!containerRef.value || !photoRef.value || !infoRef.value) return;

  const { clientX, clientY } = e;
  const rect = containerRef.value.getBoundingClientRect();

  // 计算鼠标在容器内的相对位置（-0.5到0.5之间）
  const xPos = ((clientX - rect.left) / rect.width - 0.5) * 2;
  const yPos = ((clientY - rect.top) / rect.height - 0.5) * 2;

  // 应用视差效果到照片
  gsap.to(photoRef.value, {
    x: xPos * 30, // 增加位移幅度
    y: yPos * 30, // 增加位移幅度
    rotateX: -yPos * 8, // 增加旋转幅度
    rotateY: xPos * 8, // 增加旋转幅度
    scale: 1.05, // 鼠标悬停时轻微放大
    duration: 1.2, // 动画时间稍长，更平滑
    ease: 'power3.out'
  });

  // 为信息面板添加轻微的反向视差效果
  gsap.to(infoRef.value, {
    x: -xPos * 15, // 增加反向位移幅度
    y: -yPos * 15, // 增加反向位移幅度
    duration: 1.2, // 动画时间稍长
    ease: 'power3.out'
  });
};

const handleMouseLeave = () => {
  if (!photoRef.value || !infoRef.value) return;
  // 鼠标离开时恢复原始状态
  gsap.to(photoRef.value, {
    x: 0,
    y: 0,
    rotateX: 0,
    rotateY: 0,
    scale: 1,
    duration: 1.2,
    ease: 'elastic.out(1, 0.5)' // 使用弹性缓动效果
  });
  gsap.to(infoRef.value, {
    x: 0,
    y: 0,
    duration: 1.2,
    ease: 'elastic.out(1, 0.5)'
  });
};

onMounted(() => {
  // 初始化 默认滚到顶部
  if (photoRef.value) {
    // 滚动到顶部
    window.scrollTo(0, 0);
  }
  // 照片加载动画
  const tl = gsap.timeline();

  tl.from(photoRef.value, {
    scale: 0.8, // 初始缩放更小
    opacity: 0,
    duration: 1.5, // 动画时间更长
    ease: 'power4.out'
  })
    .from(infoRef.value, {
      y: 50, // 从下方滑入
      opacity: 0,
      duration: 1, // 动画时间更长
      ease: 'power4.out'
    }, "-=1") // 与照片动画同时或稍后开始
    .from(controlsRef.value, {
      y: 30,
      opacity: 0,
      duration: 1, // 动画时间更长
      ease: 'power4.out'
    }, "-=0.8");

  // 添加视差效果事件监听
  if (containerRef.value) {
    containerRef.value.addEventListener('mousemove', handleMouseMove);
    containerRef.value.addEventListener('mouseleave', handleMouseLeave);
  }
});

onUnmounted(() => {
  // 移除视差效果事件监听
  if (containerRef.value) {
    containerRef.value.removeEventListener('mousemove', handleMouseMove);
    containerRef.value.removeEventListener('mouseleave', handleMouseLeave);
  }
});
</script>

<template>
  <div class="photo-view" ref="containerRef" v-if="photo">
    <div class="photo-container">
      <div class="photo-wrapper" ref="photoRef">
        <img v-if="photo.url" :src="photo.url" :alt="photo.title" class="photo" />
        <!-- 如果图片加载失败，显示背景色 -->
        <div v-else class="photo-fallback">
          <span>图片无法加载</span>
        </div>
      </div>

      <div class="photo-info" ref="infoRef">
        <h1>{{ photo.title }}</h1>
        <p v-if="photo.description">{{ photo.description }}</p>
        <span class="photo-date">{{ photo.date }}</span>
        <div class="album-info" v-if="album">
          <span>来自相册: {{ album.title }}</span>
        </div>
      </div>
    </div>

    <div class="photo-controls" ref="controlsRef">
      <button class="control-button back-button" @click="goBack">
        <span class="icon">←</span> 返回相册
      </button>

      <div class="navigation-controls">
        <button class="control-button prev-button" @click="navigateToPhoto(prevPhoto)" :disabled="!prevPhoto">
          <span class="icon">←</span> 上一张
        </button>

        <button class="control-button next-button" @click="navigateToPhoto(nextPhoto)" :disabled="!nextPhoto">
          下一张 <span class="icon">→</span>
        </button>
      </div>
    </div>
  </div>

  <div class="photo-not-found" v-else>
    <h2>照片未找到</h2>
    <p>抱歉，无法找到您请求的照片。</p>
    <button class="control-button back-button" @click="goBack">
      <span class="icon">←</span> 返回相册
    </button>
  </div>
</template>

<style scoped>
.photo-view {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  min-height: 100vh;
  perspective: 1000px;
  opacity: 1;
  /* Initial opacity for transition */
  transition: opacity 0.5s ease-in-out;
  /* Add transition for page change */
}

.photo-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 3rem;
  margin-bottom: 2rem;
}

.photo-wrapper {
  position: relative;
  overflow: hidden;
  border-radius: 15px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
  background-color: #f5f5f5;
  aspect-ratio: 4/3;
  transform-style: preserve-3d;
}

.photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.photo-fallback {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e0e0e0;
  color: #757575;
  font-size: 1.2rem;
}

.photo-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.photo-info h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  color: var(--color-heading);
}

.photo-info p {
  font-size: 1.2rem;
  line-height: 1.6;
  color: var(--color-text);
  margin-bottom: 1rem;
}

.photo-date {
  font-size: 1rem;
  color: var(--color-text-light);
  margin-bottom: 0.5rem;
}

.album-info {
  font-size: 1rem;
  color: var(--color-text-light);
}

.photo-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 2rem;
}

.control-button {
  display: inline-flex;
  align-items: center;
  padding: 0.8rem 1.5rem;
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s ease;
}

.control-button:hover {
  background-color: var(--color-primary-dark);
}

.control-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.control-button .icon {
  margin-right: 0.5rem;
}

.navigation-controls {
  display: flex;
  gap: 1rem;
}

.photo-not-found {
  text-align: center;
  padding: 4rem 2rem;
}

.photo-not-found h2 {
  font-size: 2rem;
  color: var(--color-heading);
  margin-bottom: 1rem;
}

.photo-not-found p {
  font-size: 1.2rem;
  color: var(--color-text);
  margin-bottom: 2rem;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .photo-container {
    grid-template-columns: 1fr;
    gap: 2rem;
  }

  .photo-info {
    text-align: center;
  }

  .photo-controls {
    flex-direction: column;
    gap: 1.5rem;
  }

  .navigation-controls {
    flex-direction: column;
    gap: 1rem;
    width: 100%;
  }

  .control-button {
    justify-content: center;
    width: 100%;
  }
}
</style>